package com.pesking.core.sqlparser.processor;

import java.util.Arrays;
import java.util.List;

import com.pesking.core.parameter.Parameter;
import com.pesking.core.sqlparser.exception.SQLRuntimeException;
import com.pesking.core.sqlparser.parameter.SqlParameter;
import com.pesking.core.sqlparser.parameter.SqlParameterProcessor;
import com.pesking.core.util.LogUtils;
import com.pesking.core.util.StringUtils;
import com.pesking.unified.auth.CurrentUser;
import com.pesking.unified.auth.PopedomManage;

/**
 * 当前用户的SQL参数处理器
 * @author cypei
 *
 */

public class CurrentUserSqlParameterHandler extends SqlParameterProcessor {

	
	@Override
	public void handle(StringBuilder sbSQL,Parameter parameter, List<SqlParameter> processors,SqlParameter sqlParameter) {
		String param = sqlParameter.getName();
		String defaultValue = sqlParameter.getValue();
		LogUtils.info(getSqlParameterType() + " 参数名称：" + param + " 默认值：" + defaultValue);
		if (StringUtils.isBlank(param)){
			throw new SQLRuntimeException("当前用户参数使用方法：[CUR_USER:loginName|nickName|id|userType|phone|email|deptId|deptName]");
		}
		CurrentUser cui = PopedomManage.getCurrentUserInfo();
		String value = "";
		if (cui != null){
			if ("admin".equals(param)) {
				if (cui.isAdmin()) {
					value = "'true'";
				}
				else {
					value = "'false'";
				}
			}
			else {
				value = cui.getFieldValue(param);
			}
		}
		else{
			throw new SQLRuntimeException("当前用户为空，参数替换失败.");
		}
		
		if (StringUtils.isBlank(value) && !StringUtils.isBlank(defaultValue)) {
			value = defaultValue;
		}
		if (value == null) {
			value = "";
		}
//		LogUtils.info(this.getSqlParameterType() + " 最后输出结果值：‘" + value + "'");
		sbSQL.append(value);
//		if ("deptId".equals(param)){
//			System.out.println("测试输出结果：" + sbSQL.toString());
//		}

	}
	
	@Override
	public int getOrder() {
		return 0;
	}


	@Override
	public List<String> getSqlParameterType() {
		return Arrays.asList(new String []{"CUR_USER"});
	}
}
